using System;
using System.Reflection;
using Common.Logging;
using NServiceBus;
using NServiceBus.Config;
using NServiceBus.Management;
using NServiceBus.Management.Config;
using NServiceBus.Management.Managers;
using NServiceBus.Management.Messages.EndpointStatusMessages;
using NServiceBus.Management.Messages.EndpointCommandMessages;
using NServiceBus.Unicast.Config;
using NServiceBus.Unicast.Transport;
using NServiceBus.Unicast.Transport.Msmq.Config;

namespace Subscriber2
{
    class Program
    {
        static void Main()
        {
            LogManager.GetLogger("hello").Debug("Started.");
            ObjectBuilder.CastleFramework.Builder builder = new ObjectBuilder.CastleFramework.Builder();

            Configure.With(builder).SagasAndMessageHandlersIn(typeof(EndpointCommandManager).Assembly);

            new ConfigMsmqTransport(builder)
                .IsTransactional(true)
                .PurgeOnStartup(false)
                .UseXmlSerialization(false);

            new ConfigUnicastBus(builder)
                .ImpersonateSender(false)
                .SetMessageHandlersFromAssembliesInOrder(typeof(EndpointCommandManager).Assembly);

            new ConfigManagement(builder);

            ITransport transport = builder.Build<ITransport>();
            IBus bClient = builder.Build<IBus>();
            EndpointManager manager = builder.Build<EndpointManager>();

            manager.Start();

            bClient.Subscribe(typeof(EndpointStatusMessage));
            bClient.Subscribe(typeof(EndpointPingCommand));
            bClient.Subscribe(typeof(EndpointPingResponseCommand));
            bClient.Start();

            transport.TransportMessageReceived += HandleTransportMessageReceived;

            Console.WriteLine("Listening for events. To exit, press 'q' and then 'Enter'.");
            while (Console.ReadLine().ToLower() != "q")
            {
            }
        }

        private static void HandleTransportMessageReceived(object sender, TransportMessageReceivedEventArgs eventArgs)
        {
            foreach(IMessage mess in eventArgs.Message.Messages)
            {
                Console.Write("Message received, message type: " + mess.GetType() + "\n");                
            }
        }
    }
}
